<template>
  <div>
    实时订单
    <a-button type="primary" @click="fresh">刷新</a-button>

    <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvent">
      <template #description="{ row }">
        <div>
          <div v-for="(desc, ind) in row.description" :key="ind">
            【<span>{{ desc.name }}</span>
            <span>X{{ desc.count }}</span>
            <span>￥{{ desc.price }}</span
            >】
          </div>
        </div>
      </template>
      <template #state="{ row }">
        {{ row.state == '1' ? '待接单' : '' }}
      </template>
      <template #action="{ row }">
        <a-button type="primary" @click="receiveOrder(row)">接单</a-button>
        <a-button type="default" @click="printOrder(row)" :loading="printing">打印</a-button>
      </template>
    </vxe-grid>
  </div>
</template>

<script setup>
import { VxeUI } from 'vxe-pc-ui'
import { message } from 'ant-design-vue';
import { reactive, toRefs, ref, watchEffect } from 'vue'
import useLive from '@renderer/api/useLive.js'
const { gridOptions } = useLive()
import XEUtils from 'xe-utils'
import useNoticeStore from '@renderer/store/modules/notice'
import request from '@renderer/plugins/axios'
const xGrid = ref()

let noticeStore = useNoticeStore()
let notices = ref(noticeStore.notices)
const receiveOrder = async (record) => {
  await request.post(`api/admin/delivery/receive`, {
    order_id: record.order_id,
    delivery_id: record.id
  })
  xGrid.value.commitProxy('query')
}
const fresh = () => {
  xGrid.value.commitProxy('query')
}
watchEffect(() => {
  notices.value.length
  if (xGrid.value) {
    xGrid.value.commitProxy('query')
  }
})

const gridEvent = {
  proxyQuery() {
    const grid = xGrid.value
    // 获取表格中的数据
    // const data = grid.getTableData().fullData;
    // console.log(data);
  },
  proxyDelete() {
    console.log('数据代理删除事件')
  },
  proxySave() {
    console.log('数据代理保存事件')
  }
}
const printing = ref(false);

const printOrder = async (record) => {
  try {
    printing.value = true;
    // 创建一个可序列化的订单对象
    const printData = {
      ticket_id: record.ticket_id,
      created_at: record.created_at,
      address: record.address,
      phone: record.phone,
      description: record.description.map(item => ({
        name: item.name,
        count: item.count,
        price: item.price
      })),
      // 添加其他需要打印的字段
      total: record.description.reduce((sum, item) => sum + (item.price * item.count), 0)
    };

    const result = await window.api.printOrder(printData);
    console.log(result)
    if (result) {
      message.success('操作成功');
    } else {
      message.error('打印失败');
    }
  } catch (error) {
    console.error('打印错误:', error);
    message.error('打印出错');
  } finally {
    printing.value = false;
  }
};
</script>

<style lang="scss" scoped>
.txt {
  font-size: 12px;
  max-width: 120px;
}
</style>
